
//
//  YpViewController.m
//  KIASupervisory
//
//  Created by apple on 15/7/19.
//  Copyright (c) 2015年 MyCompany. All rights reserved.
//

#import "WyHomeListViewController.h"
#import "WyHomeViewController.h"
#import "MainViewController.h"
#import "YoukeViewController.h"
#import "MJRefresh.h"

@interface WyHomeListViewController ()

@property (nonatomic, strong) NSMutableArray *wzList;
@property (nonatomic, strong) UIButton *back;
@property (nonatomic, strong) NetworkManager *networkManager;
@property (nonatomic, strong) MBProgressHUD *HUD;
@property (retain, nonatomic) IBOutlet UITableView *tableView;
@property (retain, nonatomic) IBOutlet UISearchBar *searchBar;
@property (nonatomic, assign) NSInteger selectedRow;

@end

@implementation WyHomeListViewController

@synthesize dataList = _dataList;
@synthesize showData = _showData;

- (void)viewDidLoad
{
    [self.navigationController setNavigationBarHidden:YES];
    [super viewDidLoad];
    self.wzList = [NSMutableArray array];
    _tableView.frame  = CGRectMake(0, 70, self.view.frame.size.width, self.view.frame.size.height-70);
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [[self view] addSubview:[self tableView]];
    self.networkManager = [[NetworkManager alloc] init];
    self.HUD = [[MBProgressHUD alloc] initWithView:self.view];
    [self.view addSubview:self.HUD];
    self.HUD.delegate = self;
    [self setupRefresh];
}


/**
 为了保证内部不泄露，在dealloc中释放占用的内存
 */
- (void)dealloc
{
    NSLog(@"MJTableViewController--dealloc---");
}


/**
 *  集成刷新控件
 */
- (void)setupRefresh
{
    // 1.下拉刷新(进入刷新状态就会调用self的headerRereshing)
    [self.tableView addHeaderWithTarget:self action:@selector(headerRereshing)];
    [self.tableView headerBeginRefreshing];
    // 设置文字(也可以不设置,默认的文字在MJRefreshConst中修改)
    self.tableView.headerPullToRefreshText = @"下拉可以刷新了";
    self.tableView.headerReleaseToRefreshText = @"松开马上刷新了";
    self.tableView.headerRefreshingText = @"智慧管家正在帮你刷新中...";
    
}


#pragma mark 开始进入刷新状态
- (void)headerRereshing
{
    // 1秒后刷新表格UI
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 刷新表格
        [self.tableView reloadData];
        
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
        [self.tableView headerEndRefreshing];
    });
}


- (IBAction)backToPre:(id)sender {

[self.navigationController popViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    
    [self performSelector:@selector(getWzList) withObject:nil afterDelay:0.3];
}

- (void)refreshViewByReloadData {
    [self getWzList];
}

- (void)getWzList {
    [self.wzList removeAllObjects];
    
    UserInfo *user = [UserInfo instance];
    if (self.networkManager == nil) {
        self.networkManager = [[NetworkManager alloc] init];
    }
    NSString *user_id = [user.info objectForKey:@"user_id"] ; 
    NSString *xiaoqu_id = [user.info objectForKey:@"xiaoqu_id"];
    if(xiaoqu_id == nil){
        xiaoqu_id = @"8";
    }
        NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:
                               xiaoqu_id,@"xiaoqu_id", nil];
        [self.networkManager requestWithMethod:getWenzhangList parameter:param delegate:self];
        [self.HUD show:YES];
 
}

#pragma mark - UITableViewDataSource methods
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [self.wzList count];
}

- (void)network:(NetworkManager *)net methodId:(RequestMethodId)methodId didRequestFinishedWithResult:(id)data {
    [self.HUD hide:YES];
    if (methodId == getWenzhangList || methodId == searchWenzhang) {
        if ([data isKindOfClass:[NSDictionary class]]) {
            NSString * result = [data objectForKeyOrNil:@"result"];
            if([result isEqualToString:@"000"]){
                
                [self.wzList removeAllObjects];
                    NSArray *results = [data objectForKeyOrNil:@"wenzhangList"];
                    if (![results isKindOfClass:[NSNull class]] && [results count] > 0) {
                        [self.wzList  addObjectsFromArray:results];
                    }
              
                
                [self.tableView reloadData];
            } else if([result isEqualToString:@"001"]){
                NSString * resultinfo = [data objectForKeyOrNil:@"resultinfo"];
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                                message:[resultinfo stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]
                                                               delegate:nil
                                                      cancelButtonTitle:@"确定"
                                                      otherButtonTitles:nil];
                [alert show];
            }
        }
    }
}

- (void)network:(NetworkManager *)net methodId:(RequestMethodId)methodId didRequestFailedWithError:(NSError *)error {
    NSDictionary *errorInfo = error.userInfo;
    NSString *msg = [errorInfo objectForKeyOrNil:@"errorMsg"];
    
    NSInteger code = error.code;
    if (code != 1) {
        if ([msg length] == 0) {
            msg = @"历史未完成问题获取失败，请稍后重试";
        }
    }
    
    if ([msg length] > 0) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                        message:msg
                                                       delegate:nil
                                              cancelButtonTitle:@"确定"
                                              otherButtonTitles:nil];
        [alert show];
    }
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *WuyeListCell = @"WuyeListCell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:
                             WuyeListCell];
    
    if (cell == nil) {
        cell = [[UITableViewCell alloc]
                initWithStyle:UITableViewCellStyleDefault
                reuseIdentifier:WuyeListCell];
    }
    if (self.wzList != nil && self.wzList.count >0) {
        NSUInteger row = [indexPath row];
        UILabel *titleLbl = (UILabel *)[cell.contentView viewWithTag:101];
        UILabel *fabuDateLbl = (UILabel *)[cell.contentView viewWithTag:102];
        UILabel *idLbl = (UILabel *)[cell.contentView viewWithTag:103];
        NSDictionary* dic = [self.wzList objectAtIndex:row];
        NSLog(@"the title is %@",[dic objectForKey:@"title"]);
        NSLog(@"the fabuDate is %@",[dic objectForKey:@"fabuDate"]);
        idLbl.text = [NSString stringWithFormat:@"%@",[dic objectForKey:@"id"]];
        NSString *unicodeStr = [[dic objectForKey:@"title"] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        titleLbl.text = unicodeStr;
        fabuDateLbl.text = [dic objectForKey:@"fabuDate"];
    }
    return cell;
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText;
{
   
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    NSInteger row = indexPath.row;
    self.selectedRow = row;
    
    if ([self.wzList count] > row) {
        if ([self.wzList count] > row) {
            WyHomeViewController *reportVC = (WyHomeViewController *)[self.storyboard instantiateViewControllerWithIdentifier:@"WyHomeViewController"];
            NSDictionary *wzInfo = [self.wzList objectAtIndex:row];
            reportVC.wzInfo = wzInfo;
            [self.navigationController pushViewController:reportVC animated:YES];            
        }
    }
}


-(void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    [self searchBar:self.searchBar textDidChange:nil];
    UserInfo *user = [UserInfo instance];
    if (self.networkManager == nil) {
        self.networkManager = [[NetworkManager alloc] init];
    }
    NSString *xiaoqu_id = [user.info objectForKey:@"xiaoqu_id"];
    xiaoqu_id  = @"8";
    NSDictionary *param1 = [NSDictionary dictionaryWithObjectsAndKeys:
                            self.searchBar.text,@"search_content",
                            xiaoqu_id,@"xiaoqu_id", nil];
    
    [self.networkManager requestWithMethod:searchWenzhang parameter:param1 delegate:self];
    [self.HUD show:YES];

    [_searchBar resignFirstResponder];
}

- (void)searchBarCancelButtonClicked:(UISearchBar *) searchBar
{
    [self searchBar:self.searchBar textDidChange:nil];
    [_searchBar resignFirstResponder];
}


@end